#include <time.h>
#include <stdio.h>

#include "../inc/wlc_bench.h"

#define ANSI 5
#define TIMER ANSI

static bench_ctx g_bench;

void bench_reset(void)
{
    g_bench.total = 0;
}

void bench_before(void)
{
    g_bench.before = clock();
}

void bench_after(void)
{
    long long result;

    g_bench.after = clock();
    result = (g_bench.after - g_bench.before) * 1000000 / CLOCKS_PER_SEC;
    g_bench.total += result;
}

void bench_compute(int benches)
{
    g_bench.result = (double)g_bench.total / benches;
}

void bench_print(void)
{
    util_print("%9.2f us", g_bench.result);

    if (g_bench.result < 0)
    {
        util_print(" (overflow or bad overhead estimation)\n");
    }
    else
    {
        util_print("\n");
    }
}

unsigned long long bench_total(void)
{
    return g_bench.total;
}

void bench_ctx_reset(bench_ctx * ctx) {
    ctx->total = 0;
}

void bench_ctx_before(bench_ctx * ctx)
{
    ctx->before = clock();
}

void bench_ctx_after(bench_ctx * ctx)
{
    long long result;

    ctx->after = clock();
    // microsecond
    result = (ctx->after - ctx->before) * 1000000 / CLOCKS_PER_SEC;
    ctx->total += result;
}

void bench_ctx_compute(bench_ctx * ctx, int benches)
{
    ctx->result = (double)ctx->total / benches;
}


void bench_ctx_print(const bench_ctx * ctx, const char *label)
{
    util_print("BENCH: %s %*c = ", label, (int)(32 - strlen(label)), ' ');
    util_print("%9.2f us", ctx->result);

    if (ctx->result < 0)
    {
        util_print(" (overflow or bad overhead estimation)\n");
    }
    else
    {
        util_print("\n");
    }
}